package com.slg.android.manyanime;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.slg.android.manyanime.adapter.HuaAdapter;
import com.slg.android.manyanime.adapter.WatchUserAdapter;
import com.slg.android.manyanime.bean.CartoonDetail;
import com.slg.android.manyanime.bean.Collection;
import com.slg.android.manyanime.utils.ApiUtils;
import com.slg.android.manyanime.utils.DataStore;
import com.slg.android.manyanime.utils.NetUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class CartoonDetailActivity extends FragmentActivity implements View.OnClickListener {

    @ViewInject(R.id.common_loading)
    private RelativeLayout loading;

    @ViewInject(R.id.common_loading_image)
    private ImageView loadingImg;

    @ViewInject(R.id.cartoon_detail_artist)
    private TextView artist;

    @ViewInject(R.id.cartoon_detail_brief_info)
    private TextView brifeinfo;

    @ViewInject(R.id.cartoon_detail_carimg)
    private ImageView cardImg;

    @ViewInject(R.id.cartoon_detail_lastup)
    private TextView lastup;

    @ViewInject(R.id.cartoon_detail_scoreimg)
    private ImageView scoreimg;

    @ViewInject(R.id.cartoon_detail_startread)
    private Button startread;

    @ViewInject(R.id.cartoon_detail_updatetime)
    private TextView updatatime;

    @ViewInject(R.id.cartoon_details_comment)
    private TextView coomment;

    @ViewInject(R.id.cartoon_details_title_back)
    private ImageView titleback;

    @ViewInject(R.id.cartoon_details_addfav)
    private ImageView addfaviote;

    @ViewInject(R.id.cartoon_detail_watcher)
    private RecyclerView watcher;

    @ViewInject(R.id.cartoon_details_share)
    private ImageView share;

    @ViewInject(R.id.cartoon_details_cartooname)
    private TextView cartName;

    @ViewInject(R.id.cartoon_detail_grid_lianzai)
    private GridView lianzaiGrid;

    @ViewInject(R.id.cartoon_detail_grid_fanwai)
    private GridView fanwaiGrid;

    @ViewInject(R.id.cartoon_detail_grid_juan)
    private GridView juanGrid;

    @ViewInject(R.id.cartoon_detail_score)
    private TextView scoretext;

    @ViewInject(R.id.juanlinear)
    private LinearLayout juanlinear;

    @ViewInject(R.id.fanwailinear)
    private LinearLayout fanwailinear;

    @ViewInject(R.id.cartoon_details_lastread)
    private TextView lastread;


    private String id;
    private CartoonDetail detail;
    private Animation loadAnimation;

    //是否已经读

    SharedPreferences preferences;
    private int type;
    private int hua;
    private boolean collected;
    private DbUtils db;

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_cartoon_detail);
        ViewUtils.inject(this);
        watcher.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        detail = new CartoonDetail();
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        db = DataStore.getDataStore().getDb();

        if (TextUtils.isEmpty(id)) {
            cartName.setText(R.string.video_id_not_found);
            scoreimg.setImageResource(R.drawable.face_1);
        } else {
            try {
                List<Collection> all = db.findAll(Collection.class);
                if (all != null) {
                    for (Collection collection : all) {
                        if (TextUtils.equals(id, collection.getId())) {
                            addfaviote.setImageResource(R.drawable.cancel_fav);
                            collected = true;
                            break;
                        }
                    }
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
            titleback.setOnClickListener(this);
            startread.setOnClickListener(this);
            if (NetUtil.isConnectInternet(this) && id != null) {
                loading.setVisibility(View.VISIBLE);
                loadAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_common_rotate);
                loadingImg.startAnimation(loadAnimation);
                parseData(id);
            }

            preferences = this.getSharedPreferences("READ", this.MODE_PRIVATE);
            type = preferences.getInt("TYPE", 0);
            hua = preferences.getInt("HUA", 0);
            if (type != 0 && hua != 0) {
                lastread.setVisibility(View.VISIBLE);
                lastread.setText("您上一次观看到第" + hua + "话");
            }
            addfaviote.setOnClickListener(this);

        }
    }


    public void parseData(String id) {
        HttpUtils utils = new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET,
                ApiUtils.CARTOON_DETAILS + id,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> stringsResponseInfo) {
                        String result = stringsResponseInfo.result;
                        if (result != null) {
                            try {
                                JSONObject object = new JSONObject(result);
                                detail.parseJson(object);
                                loadAnimation.cancel();
                                loading.setVisibility(View.GONE);
                                setData();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        loadAnimation.cancel();
                        loading.setVisibility(View.GONE);

                    }
                }
        );
    }

    public void setData() {
        Log.i("str", detail.toString());
        BitmapUtils bitmapUtil = DataStore.getBitmapUtils();
        if (detail != null) {
            artist.setText(detail.getArtist());
            brifeinfo.setText(detail.getIntro());
            bitmapUtil.configDefaultLoadingImage(R.drawable.cartoon_hot_loading);
            bitmapUtil.display(cardImg, detail.getCover());

            lastup.setText("更新至" + detail.getLastup());
            Double score = Double.parseDouble(detail.getScore());
            if (score >= 8.0) {
                scoreimg.setImageResource(R.drawable.face_5);
            } else if (score >= 7.0) {
                scoreimg.setImageResource(R.drawable.face_4);
            } else {
                scoreimg.setImageResource(R.drawable.face_3);
            }
            scoretext.setText(score + "分");
            if (detail.getIsOver().equals(1)) {
                updatatime.setText("以及完结");
            } else if (!TextUtils.isEmpty(detail.getUpdate_time())) {
                updatatime.setText("更新时间" + detail.getUpdate_time());
            }

            cartName.setText(detail.getName());
            if (detail.getWatches() != null) {
                WatchUserAdapter adapter = new WatchUserAdapter(CartoonDetailActivity.this, detail.getWatches());
                Log.i("str", "watches" + detail.getWatches().toString());

                watcher.setAdapter(adapter);

            }
            lianzaiGrid.setAdapter(new HuaAdapter(this, detail.getHuas(), 1, detail.getName()));


            if (detail.getFanwai().size() == 0) {
                fanwailinear.setVisibility(View.GONE);
            } else {
                fanwaiGrid.setAdapter(new HuaAdapter(this, detail.getFanwai(), 2, detail.getName()));
            }

            if (detail.getJuan().size() == 0) {
                juanlinear.setVisibility(View.GONE);
            } else {
                juanGrid.setAdapter(new HuaAdapter(this, detail.getJuan(), 3, detail.getName()));
            }
            coomment.setText("评论数(" + detail.getComment_num() + ")");
            coomment.setOnClickListener(this);


        }
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        Intent intent = null;
        switch (viewId) {
            case R.id.cartoon_details_title_back:
                finish();
                break;
            case R.id.cartoon_details_addfav:
//               R.id.common_collect_imageView:
                if (collected) {
                    try {
                        collected = false;
                        db.delete(Collection.class, WhereBuilder.b("id", "=", id));
                        Toast.makeText(this, "已从收藏中移除", Toast.LENGTH_SHORT).show();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    addfaviote.setImageResource(R.drawable.bt_main_fav);
                } else {
                    try {
                        Collection collection = new Collection();
                        collection.setPic(detail.getCover());
                        collection.setPic(detail.getCover());
                        collection.setIsOver(detail.getIsOver());
                        collection.setLastUp(detail.getLastup());
                        collection.setCurNum(detail.getLastup());
                        collection.setType("book");
                        collection.setName(detail.getName());
                        collection.setTotalNum(detail.getScore_total_num());
                        collection.setId(id);
                        db.saveBindingId(collection);
                        collected = true;
                        addfaviote.setImageResource(R.drawable.cancel_fav);
                        Toast.makeText(this, "已添加到收藏", Toast.LENGTH_SHORT).show();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }

                Toast.makeText(this, "已经加到收藏夹了", Toast.LENGTH_LONG).show();
                break;


            case R.id.cartoon_details_share:
                break;
            case R.id.cartoon_detail_startread:
                intent = new Intent(this, ReadCartoonActivity.class);
                ArrayList<String> arrayList = new ArrayList<String>();
                for (int i = 0; i < detail.getHuas().size(); i++) {
                    arrayList.add(detail.getHuas().get(i).getId());
                }
                String firstId = arrayList.get(0);
                ArrayList<String> urlPages = getPageUrl(firstId);
                if (pagesLoaded = true) {
                    intent.putStringArrayListExtra("hualist", arrayList);
                    intent.putStringArrayListExtra("pageslist", urlPages);
                    intent.putExtra("hua", 1);
                    intent.putExtra("type", 1);
                    intent.putExtra("cartName", detail.getName());
                    intent.putExtra("huaName", detail.getHuas().get(0).getName());
                    Log.i("pageslist", urlPages.toString());
                    //1代表连载，2代表番外，3代表单行卷
                    startActivityForResult(intent, 0);
                }
                break;
            case R.id.cartoon_details_comment:
                intent = new Intent(this, CommentActivity.class);
                intent.putExtra("type", "book");
                intent.putExtra("mid", detail.getId());
                startActivity(intent);
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                Bundle b = data.getExtras();
                hua = b.getInt("read_position");
                type = b.getInt("type");
                SharedPreferences.Editor edit = preferences.edit();
                edit.putInt("TYPE", type);
                edit.putInt("HUA", hua);
                break;

        }
    }

    boolean pagesLoaded = false;

    public ArrayList<String> getPageUrl(String id) {
        final ArrayList<String> pageUrls = new ArrayList<>();
        HttpUtils utils = new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET
                , ApiUtils.CARTOON_PAGES + id,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                        String result = stringResponseInfo.result;
                        try {
                            JSONArray array = new JSONArray(result);
                            for (int i = 0; i < array.length(); i++) {
                                String str = array.getString(i);
                                pageUrls.add(str);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        pagesLoaded = true;

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }
                });
        return pageUrls;

    }
}
